package de.jmda.cbo.user;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

public class JUTUser
{
	private static final String PERSISTENCE_UNIT_NAME = "jmda.home.jpa";

	private static EntityManagerFactory factory;

	public static void main(String[] args)
	{
		factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

		EntityManager em = factory.createEntityManager();

		// initially read the existing entries and write to console
		TypedQuery<User> q = em.createNamedQuery("getUserAll", User.class);

		List<User> users = q.getResultList();

		for (User user : users)
		{
			System.out.println(user.asString());
		}
		
		int size = users.size();

		System.out.println("size: " + size);

		// create new system user
		em.getTransaction().begin();

		User user =
				new User("username_" + size, "password_" + size, "email_" + size);
		em.persist(user);
		
		em.getTransaction().commit();
		
		// again read the existing entries and write to console
		users = q.getResultList();

		for (User user2 : users)
		{
			System.out.println(user2.asString());
		}
		
		size = users.size();

		System.out.println("size: " + size);

		em.close();

		factory.close();
	}
}